// pages/ai_chat/ai_chat_page.dart (*** NEW ***)
import 'package:flutter/material.dart';

import '../../bloc/ai_chat/ai_chat_state.dart' hide ChatMessage;




import 'chat_message.dart';


class AiPage extends StatefulWidget  {
  const AiPage({super.key});

  @override
  State<AiPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<AiPage>
{
  final
  TextEditingController _messageController = TextEditingController();
  final
  ScrollController _scrollController = ScrollController();

  // Initial chat messages (mimicking the screenshot flow)
  final List<ChatMessage> _messages = [
    LoadingMessage(),
    AiResponseMessage(
      content:
      '受XXXXXXXXXXXXXXX有限公司委托，我分析了从2021年01月01日至2024年11月30日购销链风险、发票风险及增值税、企业所得税等税收风险，得出以下结论：共检测8项风险指标结果：其中：高风险3项/中风险0项/低风险0项/无其他等级风险，可能涉及虚开金额0万元（取消项影响金额）以上，或涉及接受虚开金额310万元以上，预计影响增值税0万元（取消项影响税额，根据纳税人类型选择）以上。'
      ,
    ),
    SuggestedQuestionsMessage(
      questions: [
        '如何避免后续出现的风险？', '具体是哪一张发票出了问题？'
      ],
    ),
    ActionButtonsMessage(
      buttonTexts: [
        '税款确认', '工资确认', '进项发票勾选确认'
      ],
    ),
  ];

  @override
  void
  initState() {
    super.initState();
    // Simulate initial loading message and then display content
    Future.delayed(
        const Duration(seconds: 2
        ), () {
      if
      (mounted) {
        setState(() {
          _messages.insert(
              0, AiResponseMessage(content: '请稍后，正在分析贵公司企业数据。')); // This is the "loading" message
          // In a real scenario, you'd fetch actual data and replace the loading message
        });
        _scrollToBottom();
      }
    });

    // Automatically scroll to bottom on new messages
    // This is a simplified approach, often you'd listen to _messages.length changes
    // or call _scrollToBottom after adding a message.
  }

  @override
  void
  dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super
        .dispose();
  }

  // --- Helper Functions for UI elements ---

  // Function to build a message bubble based on type
  Widget _buildMessageBubble(ChatMessage message) {
    switch
    (message.type) {
      case
      MessageType.loading:
        return
          _buildLoadingMessage();
      case
      MessageType.aiResponse:
        return _buildAiResponse(message as
        AiResponseMessage);
      case
      MessageType.suggestedQuestions:
        return _buildSuggestedQuestions(message as
        SuggestedQuestionsMessage);
      case
      MessageType.actionButtons:
        return _buildActionButtons(message as
        ActionButtonsMessage);
      case
      MessageType.userMessage:
        return _buildUserMessage(message as UserMessage); // Added for completeness, though not in screenshot
      default
          :
        return const SizedBox.shrink(); // Fallback
    }
  }

  // Type 1: Loading/Thinking Message
  Widget _buildLoadingMessage() {
    return
      Align(
        alignment: Alignment.centerLeft,
        child: Container(
          margin:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0
          ),
          padding:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0
          ),
          decoration: BoxDecoration(
            color: Colors.grey[
            100
            ],
            borderRadius: BorderRadius.circular(
                8.0
            ),
          ),
          child:
          const
          Text(
            '请稍后，正在分析贵公司企业数据。'
            ,
            style: TextStyle(fontSize:
            15.0
                , color: Colors.black87),
          ),
        ),
      );
  }

  // Type 2: AI Response Block
  Widget _buildAiResponse(AiResponseMessage message) {
    return
      Align(
        alignment: Alignment.centerLeft,
        child: Container(
          margin:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0
          ),
          padding:
          const EdgeInsets.all(16.0
          ),
          decoration: BoxDecoration(
            color: Colors.grey[
            100
            ],
            borderRadius: BorderRadius.circular(
                8.0
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                message.content,
                style:
                const TextStyle(fontSize: 15.0
                    , color: Colors.black87),
              ),
              const SizedBox(height: 12.0
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
// Distribute icons evenly
                children: [
                  _buildActionIcon(Icons.copy,
                      '复制', () => print('复制'
                      )),
                  _buildActionIcon(Icons.volume_up_outlined,
                      '语音', () => print('语音'
                      )),
                  _buildActionIcon(Icons.bookmark_border,
                      '收藏', () => print('收藏'
                      )),
                  _buildActionIcon(Icons.share,
                      '分享', () => print('分享'
                      )),
                  _buildActionIcon(Icons.refresh,
                      '刷新', () => print('刷新'
                      )),
                ],
              ),
            ],
          ),
        ),
      );
  }

  // Helper for action icons in AI response
  Widget _buildActionIcon(IconData icon,
      String
      tooltip, VoidCallback onPressed) {
    return
      IconButton(
        icon: Icon(icon, color: Colors.grey[
        600], size: 20
        ),
        onPressed: onPressed,
        tooltip: tooltip,
        visualDensity: VisualDensity.compact,
// Make icons a bit denser
        padding: EdgeInsets.zero,
// Remove extra padding
      );
  }

  // Type 3: Suggested Questions Block
  Widget _buildSuggestedQuestions(SuggestedQuestionsMessage message) {
    return
      Container(
        margin:
        const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding:
              const EdgeInsets.only(left: 8.0, bottom: 8.0
              ),
              child: Text(
                '您可能想问'
                ,
                style: TextStyle(fontSize:
                14.0, color: Colors.grey[600
                ]),
              ),
            ),
            Wrap(
// Use Wrap to allow buttons to flow to next line
              spacing:
              8.0, // Horizontal space between buttons
              runSpacing:
              8.0, // Vertical space between lines of buttons
              children: message.questions.map((q) => _buildQuestionButton(q)).toList(),
            ),
          ],
        ),
      );
  }

  // Helper for suggested question buttons
  Widget _buildQuestionButton(
      String
      text) {
    return
      OutlinedButton(
        onPressed: () {
          print('Suggested question clicked: $text'
          );
          // Simulate sending this question as a user message
          _sendMessage(text);
        },
        style: OutlinedButton.styleFrom(
          foregroundColor: Colors.black87,
          side: BorderSide(color: Colors.grey[
          300]!, width: 1.0
          ),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(
              20.0
          )),
          padding:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0
          ),
        ),
        child: Text(text, style:
        const TextStyle(fontSize: 14.0
        )),
      );
  }

  // Type 4: Action Buttons Block
  Widget _buildActionButtons(ActionButtonsMessage message) {
    return
      Container(
        margin:
        const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0
        ),
        child: Wrap(
          spacing:
          12.0, // Horizontal space between buttons
          runSpacing:
          12.0, // Vertical space between lines of buttons
          children: message.buttonTexts.map((text) => _buildActionButton(text)).toList(),
        ),
      );
  }

  // Helper for action buttons
  Widget _buildActionButton(
      String
      text) {
    return
      Container(
        padding:
        const EdgeInsets.symmetric(vertical: 10.0, horizontal: 16.0
        ),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(
              8.0
          ),
          border: Border.all(color: Colors.grey[
          300]!, width: 1.0
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(
                  0.1
              ),
              spreadRadius:
              1
              ,
              blurRadius:
              3
              ,
              offset:
              const Offset(0, 2
              ),
            ),
          ],
        ),
        child: InkWell(
// Use InkWell for tap effect with a custom child
          onTap: () =>
              print('Action button clicked: $text'
              ),
          child: Column(
            children: [
              // Placeholder for icons if needed (e.g., Icon(Icons.check, size: 28, color: Colors.grey[600]))
              // In the screenshot, there are icons, but I'll use placeholders for simplicity,
              // you'd map text to specific icons.
              Icon(_getIconForAction(text), size:
              28, color: Colors.grey[600]), // Custom icon logic
              const SizedBox(height: 4
              ),
              Text(text, style:
              const TextStyle(fontSize: 12.0
                  , color: Colors.black87)),
            ],
          ),
        ),
      );
  }

  // Helper to get specific icons for action buttons (placeholder)
  IconData _getIconForAction(
      String
      text) {
    switch
    (text) {
      case '税款确认': return
        Icons.receipt_long;
      case '工资确认': return
        Icons.attach_money;
      case '进项发票勾选确认': return
        Icons.fact_check_outlined;
      default: return
        Icons.help_outline;
    }
  }


  // Type 5: User Message (for completeness, though not in screenshot)
  Widget _buildUserMessage(UserMessage message) {
    return
      Align(
        alignment: Alignment.centerRight,
        child: Container(
          margin:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0
          ),
          padding:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0
          ),
          decoration: BoxDecoration(
            color: Theme.of(context).primaryColor,
// Accent color for user messages
            borderRadius: BorderRadius.circular(
                8.0
            ),
          ),
          child: Text(
            message.content,
            style:
            const TextStyle(fontSize: 15.0
                , color: Colors.white),
          ),
        ),
      );
  }

  // --- Input Bar Logic ---
  void _sendMessage(String
  text) {
    if (text.trim().isEmpty) return
      ;
    setState(() {
      _messages.add(UserMessage(content: text));
    });
    _messageController.clear();
    _scrollToBottom();
    // Simulate AI response after user message (for demo)
    _simulateAiResponse(text);
  }

  void _simulateAiResponse(String
  userText) {
    Future.delayed(
        const Duration(seconds: 1
        ), () {
      setState(() {
        _messages.add(LoadingMessage());
// Show thinking state
      });
      _scrollToBottom();
    });

    Future.delayed(
        const Duration(seconds: 3
        ), () {
      if
      (mounted) {
        setState(() {
          _messages.removeLast();
// Remove loading message
          _messages.add(AiResponseMessage(content:
          '针对您关于"$userText"的问题，AI正在为您生成详细报告。'
          ));
          // Add more complex responses, suggested questions, or actions based on user input here
          _messages.add(SuggestedQuestionsMessage(questions: [
            '您想了解哪些方面的风险？', '我可以提供哪些帮助？'
          ]));
        });
        _scrollToBottom();
      }
    });
  }

  void
  _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if
      (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration:
          const Duration(milliseconds: 300
          ),
          curve: Curves.easeOut,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        appBar: AppBar(
          title:
          const Text('企税AI定制版'
          ),
          centerTitle:
          true
          ,
        ),
        body: Column(
          children: [
            // Chat messages area
            Expanded(
              child: ListView.builder(
                controller: _scrollController,
                itemCount: _messages.length,
                padding:
                const EdgeInsets.symmetric(vertical: 8.0
                ),
                itemBuilder: (context, index) {
                  return
                    _buildMessageBubble(_messages[index]);
                },
              ),
            ),
            // Input area
            Container(
              padding:
              const EdgeInsets.symmetric(horizontal: 10.0, vertical: 8.0
              ),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(top: BorderSide(color: Colors.grey[
                200]!, width: 1.0
                )),
              ),
              child: Row(
                children: [
                  IconButton(
                    icon: Icon(Icons.camera_alt_outlined, color: Colors.grey[
                    600
                    ]),
                    onPressed: () =>
                        print('Camera clicked'
                        ),
                  ),
                  Expanded(
                    child: TextField(
                      controller: _messageController,
                      decoration: InputDecoration(
                        hintText:
                        '发消息...'
                        ,
                        hintStyle: TextStyle(color: Colors.grey[
                        400
                        ]),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(
                              25.0
                          ),
                          borderSide: BorderSide.none,
// No border
                        ),
                        filled:
                        true
                        ,
                        fillColor: Colors.grey[
                        100], // Light grey background for input
                        contentPadding:
                        const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0
                        ),
                        isDense:
                        true
                        ,
                      ),
                      onSubmitted: (text) => _sendMessage(text),
// Send on enter
                      style:
                      const TextStyle(fontSize: 16.0
                          , color: Colors.black87),
                    ),
                  ),
                  IconButton(
                    icon: Icon(Icons.mic_none, color: Colors.grey[
                    600
                    ]),
                    onPressed: () =>
                        print('Voice clicked'
                        ),
                  ),
                  IconButton(
                    icon: Icon(Icons.add_circle_outline, color: Theme.of(context).primaryColor),
// Accent color
                    onPressed: () =>
                        print('Plus clicked'
                        ),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
  }
}